'use strict';

const { Controller } = require('ee-core');
const Log = require('ee-core/log');
const Services = require('ee-core/services');

const { app, BrowserWindow, dialog, ipcRenderer } = require('electron');
const Database = require('better-sqlite3');
const fs = require('fs');
const path = require('path') // 添加这一行
const XLSX = require('xlsx')

const { session, shell } = require('electron')


/**
 * example
 * @class
 */
class ExampleController extends Controller {

  constructor(ctx) {
    super(ctx);
  }


  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。详情见：控制器文档
   */

  /**
   * test
   */
  async test() {
    const result = await Services.get('example').test('electron');
    Log.info('service result:', result);

    return 'hello electron-egg11111111111';
  }

  async exportExcel(args, event) {
    try {
      let data = JSON.parse(args.data)
      let exportmap = JSON.parse(args.exportmap)
      let selectedDataArray = data.map(obj => {
        // let objkeys = Object.keys(obj)
        let a = {
          拍货日期: obj.buygoodsDate,
          销售员: obj.salespersonName,
          店名: obj.storename,
          接单平台: obj.orderplatform,
          订单编号: obj.ordernumber,
          收件人: obj.recipients,
          门市地址: obj.address,
          颜色尺码: obj.colorSize,
          数量: obj.num,
          商品主图: `http://47.99.66.117:3307/imagest${obj.goodsimg}`,
          拍货链接: obj.buygoodsUrl,
          "售價（不含运费）": obj.price,
          运费: obj.freight,
          "售价（含运费）": obj.priceFreight,
          成本: obj.cost,
          结账金额: obj.closingAmount,
          "代收金額（先付的不填）": obj.collectionAmount,
          商品名称: obj.goodsName,
          电话: obj.phone,
          物流方式: obj.logistics,
          出货日期: obj.shippingDate,
          国内快递单号: obj.expressNum,
          "新竹单号/超商": obj.hsinchuNum,
          店号: obj.storeNum,
          "代收（做拍货当天就完善）": obj.collection,
          品名: obj.productName,
          备注: obj.remarks,
          重量: obj.weight,
        }
        let other = JSON.parse(obj.other)
        let b = {}
        other.forEach(item => {
          b[item.label] = item.value
        });
        let c = { ...a, ...b }
        return c;
      });

      let exportdata = []
      let exportdata2 = []

      selectedDataArray.forEach(item => {
        let a = {}
        exportmap.forEach(item2 => {
          if (item[item2.label] != undefined) {
            a[item2.label] = item[item2.label]
          }
        });
        exportdata.push(a)
      });

      exportdata.forEach(item => {
        let expressNumarr = item['国内快递单号'] == undefined ? [] : JSON.parse(item['国内快递单号'])
        let colorSizearr = item['颜色尺码'] == undefined ? [] : JSON.parse(item['颜色尺码'])
        let goodsNamearr = item['商品名称'] == undefined ? [] : JSON.parse(item['商品名称'])
        if (expressNumarr.length > 1 || colorSizearr.length > 1 || goodsNamearr.length > 1) {
          let maxLength = Math.max(expressNumarr.length, colorSizearr.length, goodsNamearr.length);
          for (let i = 0; i < maxLength; i++) {
            if (i == 0) {
              let copyitem = JSON.parse(JSON.stringify(item))
              copyitem['国内快递单号'] = expressNumarr[i]
              copyitem['颜色尺码'] = colorSizearr[i]
              copyitem['商品名称'] = goodsNamearr[i]
              exportdata2.push(copyitem)
            } else {
              let t = {
                '国内快递单号': expressNumarr[i] == undefined ? '' : expressNumarr[i],
                '颜色尺码': colorSizearr[i] == undefined ? '' : colorSizearr[i],
                '商品名称': goodsNamearr[i] == undefined ? '' : goodsNamearr[i]
              }
              exportdata2.push(t)
            }

          }
        } else {
          if (item['国内快递单号'] != undefined) {
            item['国内快递单号'] = expressNumarr[0]
          }
          if (item['颜色尺码'] != undefined) {
            item['颜色尺码'] = colorSizearr[0]
          }
          if (item['商品名称'] != undefined) {
            item['商品名称'] = goodsNamearr[0]
          }



          exportdata2.push(item)
        }
      });
      console.log(exportdata2.length);
      const result = await Services.get('example').getexportdata(exportdata2);
      return result;


    } catch (err) {
      console.log(err);
    }

  }

  async setCookie(webview) {
    webview = JSON.parse(webview)
    let ses = session.fromPartition(webview.webviewPartition)
    let cookies = await ses.cookies.get({ url: webview.url })
    if (cookies.length > 0) {
      let cookieArr = cookies.map((item) => {
        return {
          name: item.name,
          value: item.value,
        }
      })
      return cookieArr
    } else {
      return false
    }
  }

  async deleteCookie(webview) {
    webview = JSON.parse(webview)
    let ses = session.fromPartition(webview.webviewPartition)
    let cookies = await ses.cookies.get({ url: webview.url })
    if (cookies.length > 0) {
      for (let cookie of cookies) {
        await ses.cookies.remove(webview.url, cookie.name);
      }
      return true; // 返回true表示成功清除了cookie
    } else {
      return false
    }
  }

  async importCookie(args, event) {
    try {
      const result = await dialog.showOpenDialog({
        properties: ['openFile'],
        filters: [
          { name: 'DB Files', extensions: ['txt', 'TXT'] },
          // 可以添加其他文件类型的过滤器
        ],
      });
      const filePath = result.filePaths[0];
      if (!filePath) {
        console.error('No file selected');
        return null;
      }

      const fileContent = fs.readFileSync(filePath, 'utf8'); // Read file content as utf8

      return fileContent;


    } catch (err) {
      console.log(err);
    }

  }

  async getlutianorderlist(args, event) {
    const result = await Services.get('example').getorderlist(args);
    return result;
  }
// 清空所选账号缓存重新获取
  async wipecache(args, event) {
    const result = await Services.get('example').getwipecache(args);
    return result;
  }

  async savesqlitdbdatat(args) {
    const result = await Services.get('example').savesqlitDBdata(args);
    return result;
  }

  async getlutianorderdetail(args, event) {
    const result = await Services.get('example').getorderdetail(args);
    return result;
  }

  async getagentData(args, event) {
    return global.agentData;
  }

  async modifyagentData(args, event) {
    let a = JSON.parse(args)
    global.agentData = {
      address: a.address,
      port: a.port
    }
    return agentData;
  }

  async changedborder(args, event) {
    const result = await Services.get('example').changedborder(args);
    return result;
  }

  async watchmessage(args, event) {
    const result = await Services.get('example').serverWatchmessage(args);
    return result;
  }

  // 获取账号消息用户列表
  async getmessagecontacts(args, event) {
    const result = await Services.get('example').getmessagecontacts(args);
    return result;
  }

  // 第一次获取用户消息列表
  async getAccountmessage(args, event) {
    const result = await Services.get('example').getAccountmessageService(args);
    return result;
  }

  // 发送消息
  async sendmessage(args, event) {
    const result = await Services.get('example').sendmessageService(args);
    return result;
  }

  // 获取商品信息
  async getgoodsitems(args, event) {
    const result = await Services.get('example').getgoodsitemsService(args);
    return result;
  }

  // 获取订单信息
  async getorderitems(args, event) {
    const result = await Services.get('example').getorderitemsService(args);
    return result;
  }

  // 获取历史消息
  async getoldmessage(args, event) {
    const result = await Services.get('example').getoldmessageService(args);
    return result;
  }

  // 选择图片
  async selectimg(args, event) {
    const result = await Services.get('example').selectimgService(args);
    return result;
  }

  // 获取单独消息用户
  async getalonemessageuser(args, event) {
    const result = await Services.get('example').getalonemessageuserService(args);
    return result;
  }

   // 批量获取未读消息数量
   async getmessageunread(args, event) {
    const result = await Services.get('example').getmessageunreadService(args);
    return result;
  }

  // 验证cookie
   async verificationcookie(args, event) {
    const result = await Services.get('example').verificationcookieService(args);
    return result;
  }

}

ExampleController.toString = () => '[class ExampleController]';
module.exports = ExampleController;  